<template>
  <div id="container"></div>
</template>

<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader';
import { ComponentInternalInstance } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
let map: any = null;
let geocoder: any = null;
let marker: any = null;
let auto: any = null;
const props = withDefaults(defineProps<{
  address: string,
}>(), {
  address: '北京天安门'
});

const point = ref<MapLngLat>({
  lng: '',
  lat: ''
});

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: '8d7105b0c96d264a940e4a4a22a78b10',
  };
  AMapLoader.load({
    key: 'd5b85b6cf61dbbff70c4fb05cbd2435e', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Geocoder', 'AMap.AutoComplete'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '2D', // 3D / 2D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
      geocoder = new AMap.Geocoder({
        city: '000', //城市设为北京010，默认：“全国”000
      });
      marker = new AMap.Marker();
      auto = new AMap.AutoComplete({
        city: '000', //城市
        input: 'complate-input'
      });
    })
    .catch((e: any) => {
      console.log(e);
    });
});

// 根据地址获取经纬度
const getLocationLngLat = (): Promise<MapLngLat | null> => {
  return new Promise((resolve: any, reject: any) => {
    geocoder.getLocation(props.address, (status: any, result: any) => {
      if (status === 'complete' && result.geocodes.length) {
        const lnglat = result.geocodes[0].location;
        point.value = lnglat;
        markPointOnMap(lnglat);
        resolve(lnglat);
      } else {
        proxy?.$modal.msgWarning('根据地址查询位置失败，请检查后重试');
        reject(null);
      }
    });
  });
};
// 把查询地址响应的点在地图上标注出来
const markPointOnMap = (point: MapLngLat) => {
  if (!point) return;
  // 在地图上标点
  marker.setPosition(point);
  map.add(marker);
  map.setFitView(marker);
};

// 模糊查询
const searchList = ref<any[]>([]);
const searchLoading = ref<boolean>(false);

const emits = defineEmits(['searched']);
const searchAddress = (address: string) => {
  if (!auto) return;
  searchLoading.value = true;
  auto.search(address, (status: any, result: any) => {
    if (status === 'complete' && result.tips.length) {
      searchList.value = result.tips;
    } else {
      searchList.value = [];
    }
    searchLoading.value = false;
    emits('searched', searchList.value);
  });
};
defineExpose({
  getLocationLngLat,
  markPointOnMap,
  searchAddress,
  searchLoading
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<style lang="scss" scoped>
#container {
  width: 100%;
  // height: 800px;
  aspect-ratio: 1 / 1;
  margin: 10px 0;
}
</style>
